<template>
  <div>
    <div style="display: flex; justify-content: center; margin-top: 150px">
      <el-card style="width: 400px">
        <h1>用户登陆</h1>

        <el-form label-width="120px">
          <el-form-item label="用户名：">
            <el-input v-model="Data.username"></el-input>
          </el-form-item>
          <el-form-item label="密码：">
            <el-input type="password" v-model="Data.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="userLogin()">登陆</el-button>
            <el-button>取消</el-button>
          </el-form-item>
          <el-form-item label="URL">
            <el-input v-model="Data.url"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getData()">获取数据</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-form>
      <el-form-item label="数据：">
        <el-input v-model="Data.rec" type="textarea" :rows="20"></el-input>
      </el-form-item>
    </el-form>
    <div></div>
  </div>
</template>
<script setup lang="ts">
// 导入
import { reactive, ref, renderSlot } from "vue";

import { ElMessage } from "element-plus";

import axios from 'axios'

var Data = reactive({
  username: ref(""),
  password: ref(""),
  url: ref(""),
  rec: ref(""),
});

const userLogin = () => {

    axios.post("http://192.168.182.140:8000/jwt-auth/", {
        username: Data.username,
        password: Data.password,
    }).then((res)=>{
        console.log(res);

        // 判断是否有数据
        if (res.data.token){
            // 写入到localstorage 
            localStorage.setItem('token', res.data.token);
            // 把返回信息显示在下面多行文本框 
            Data.rec = JSON.stringify(res.data);
            // 显示登陆成功！
            ElMessage({
                message:'登陆成功！',
                type:'success',
            })
        } else {
             ElMessage({
                message: res.data.error,
                type: "error",
                });
        }
    })


};

const getData = () => {
  axios
    .get("http://192.168.182.140:8000/" + Data.url)
    .then((res) => {
      console.log(res);
      console.log("============");
      if (res.data.code) {
        console.log(JSON.stringify(res));
        Data.rec = JSON.stringify(res);
      } else {
        console.log(res.data.error);
        Data.rec = JSON.stringify(res);
      }
    })
    .catch((err) => {
      console.log(err);
      Data.rec = JSON.stringify(err);
    });
};
</script>
